package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.pojo.UserLocation;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.*;

@DubboService(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新用户地理位置
     *
     * @param userId    用户id
     * @param longitude 经度
     * @param latitude  纬度
     * @param address   地址名称
     * @return
     */
    @Override
    public Boolean updateUserLocation(Long userId, Double longitude, Double latitude, String address) {
        //查询用户的地理位置数据，如果有，就进行更新操作，如果没有，就插入数据

        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);
        if (null == userLocation) {
            //用户数据不存在，新增操作
            userLocation = new UserLocation();
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setUserId(userId);
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());
            userLocation.setId(ObjectId.get());

            this.mongoTemplate.save(userLocation);
        } else {
            //更新操作
            Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                    .set("address", address)
                    .set("updated", System.currentTimeMillis())
                    .set("lastUpdated", userLocation.getUpdated());
            this.mongoTemplate.updateFirst(query, update, UserLocation.class);
        }

        return true;
    }

    @Override
    public UserLocationVo queryByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return UserLocationVo.format(this.mongoTemplate.findOne(query, UserLocation.class));
    }

    /**
     * 根据位置搜索
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @param distance  距离(米)
     * @param page      页数
     * @param pageSize  页面大小
     */
    @Override
    public PageInfo<UserLocationVo> queryUserFromLocation(Double longitude, Double latitude,
                                                          Double distance, Integer page, Integer pageSize) {

        PageInfo<UserLocationVo> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        //距离
        Distance distanceObj = new Distance(distance / 1000, Metrics.KILOMETERS);

        //画一个圆圈
        Circle circle = new Circle(new GeoJsonPoint(longitude, latitude), distanceObj);

        // 设置分页参数
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("location")));
        Query query = Query.query(Criteria.where("location").withinSphere(circle)).with(pageRequest);

        List<UserLocation> userLocationList = this.mongoTemplate.find(query, UserLocation.class);
        if(CollUtil.isEmpty(userLocationList)){
            return pageInfo;
        }

        //   TODO 按照距离排序 实现思路：根据坐标进行计算 目标点与 我的点的距离  按照距离进行排序
        List<UserLocationVo> userLocationVos = UserLocationVo.formatToList(userLocationList);
        //将距离记录下来,按照距离进行排序
        HashMap<Double,UserLocationVo> hashMap = new HashMap<>();
        for (UserLocationVo userLocationVo : userLocationVos) {
            //根据坐标生成GlobalCoordinates坐标
            GlobalCoordinates source = new GlobalCoordinates(latitude, longitude);
            GlobalCoordinates target = new GlobalCoordinates(userLocationVo.getLatitude(), userLocationVo.getLongitude());
            Double meter = getDistanceMeter(source, target, Ellipsoid.Sphere);
            hashMap.put(meter,userLocationVo);
        }
        Set<Double> meters = hashMap.keySet();
        //将距离存放到ArrayList中
        ArrayList<Double> doubleArrayList = new ArrayList<>(meters);
        List<UserLocationVo> resultRecords = new ArrayList<>();
        //将距离排序
        Collections.sort(doubleArrayList);
        //测试是否排序
        //System.out.println("doubleArrayList = " + doubleArrayList);
        //按照排序后的顺序添加到新的集合中
        doubleArrayList.forEach(meter-> resultRecords.add(hashMap.get(meter)));
        pageInfo.setRecords(resultRecords);

        return pageInfo;
    }
    @Override
    public Double queryDistance(Long userId, Long targetUserId) {
        //查询出两个userId对应的UserLocation 并转换成UserLocationVo对象
        Query query1 = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation1 = mongoTemplate.findOne(query1, UserLocation.class);
        Query query2 = Query.query(Criteria.where("userId").is(targetUserId));
        UserLocation userLocation2 = mongoTemplate.findOne(query2, UserLocation.class);
        UserLocationVo locationVo1 = UserLocationVo.format(userLocation1);
        UserLocationVo locationVo2 = UserLocationVo.format(userLocation2);

        //生成GlobalCoordinates坐标
        GlobalCoordinates source = new GlobalCoordinates(locationVo1.getLatitude(), locationVo1.getLongitude());
        GlobalCoordinates target = new GlobalCoordinates(locationVo2.getLatitude(), locationVo2.getLongitude());
        //调用公共方法查询两点距离
        return getDistanceMeter(source, target, Ellipsoid.Sphere);
    }


    /**
     * 公共方法 查询两个坐标点的距离
     * @param gpsFrom
     * @param gpsTo
     * @param ellipsoid
     * @return
     */
    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){

        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);

        return geoCurve.getEllipsoidalDistance();
    }
}
